package com.aliang.shopping.model.converter;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.aliang.shopping.log.enums.LoginType;
import com.aliang.shopping.model.po.LoginLog;
import com.aliang.shopping.model.vo.loginLog.LoginLogExportVO;
import com.aliang.shopping.model.vo.loginLog.LoginLogVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;

import java.util.List;
import java.util.Objects;

/**
 * 登录日志数据转换器
 */
@Mapper(componentModel = "Spring")
public interface LoginLogConverter {


    /**
     * 将登录日志展示对象转换为登录日志导出对象
     *
     * @param vo
     * @return
     */
    @Mappings({
            @Mapping(target = "errorMsg", defaultValue = "无"),
            @Mapping(target = "loginMethod", expression = "java(getLoginMethodMsg(vo.getLoginMethod()))"),
            @Mapping(target = "status", expression = "java(CommonConverter.getMsg(vo.getStatus(),\"登录成功\",\"登录失败\"))"),
    })
    LoginLogExportVO toExportVO(LoginLogVO vo);

    List<LoginLogExportVO> toImportDTOList(List<LoginLogVO> list);

    default String getLoginMethodMsg(Integer type) {
        if (Objects.equals(type, LoginType.ACCOUNT.getDesc())) {
            return "账号登录";
        }
        if (Objects.equals(type, LoginType.EMAIL.getDesc())) {
            return "邮箱登录";
        }
        if (Objects.equals(type, LoginType.PHONE.getDesc())) {
            return "手机号登录";
        }
        return "未知";
    }


    /**
     * 关键字脱敏
     *
     * @param keyWord
     * @param type    登录方式（0账号，1邮箱，2手机号
     * @return
     */
    default String getHideKeyWord(String keyWord, Integer type) {
        if (type == 0) {
            //保留前2后1
            return StrUtil.hide(keyWord, 2, keyWord.length() - 1);
        }
        if (type == 1) {
            return DesensitizedUtil.email(keyWord);
        }
        return DesensitizedUtil.mobilePhone(keyWord);
    }


    @Mapping(target = "keyword", expression = "java(getHideKeyWord(vo.getKeyword(),vo.getLoginMethod()))")
    LoginLogVO toVO(LoginLog vo);

    List<LoginLogVO> toVOList(List<LoginLog> list);
}
